﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JCTimes.Portal.Infrastructure;
using JCTimes.DomainModel.Repository;
using JCTimes.DomainModel.Entity;
using JCTimes.Portal.Models;
using JCTimes.Portal.Specification;
using JCTimes.Portal.Models;
using System.Data;

namespace JCTimes.Portal.Controllers
{
    [Permission]
    public class AgencyController : Controller
    {
        //
        // GET: /Agency/
        private IUserRepository userRep;
        private const int pageSize = 10;

        public AgencyController(IUserRepository usrRep)
        {
            this.userRep = usrRep;
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Query users.
        /// </summary>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter conditions.</param>
        /// <returns>Users grid view</returns>
        public PartialViewResult Grid(int? pageIndex, Searcher searcher)
        {
            var pred = UserSpecification.Get_User_Pred(searcher);
            var model = new GridView<User>
            {
                Searcher = searcher,
                PagedList = userRep.GetList<User>().Where(pred).Where(m=>m.RoleID==Constant.Agency).OrderByDescending(u => u.CreateDate).ToPagedList(pageIndex ?? 1, pageSize)
            };
            return PartialView("_gridview", model);
        }

        public ActionResult Create()
        {
            return View(new User { ID = Guid.NewGuid().ToString() });
        }

        /// <summary>
        /// Add user.
        /// </summary>
        /// <param name="user">User item</param>
        /// <returns>Add result in json</returns>
        [HttpPost]
        public JsonResult Create(User user)
        {
            if (userRep.Find(u => u.UserName == user.UserName) != null)
            {
                return Json(new { Msg = "用户名已存在" });
            }
            try
            {
                user.RoleID = Constant.Agency;
                user.CreateDate = DateTime.Now;
                user.Flag = 0;
                user.Password = CM.GetMd5Password(System.Configuration.ConfigurationManager.AppSettings["Password"] + "");
                userRep.Add(user);
                userRep.SaveChanges();
                return Json(new { Msg = "创建成功", IsSuccess = true });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return Json(new { Msg = "出错了" });
            }
        }

        /// <summary>
        /// Delete user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter conditions</param>
        /// <returns></returns>
        public RedirectToRouteResult Delete(string id, int pageIndex, Searcher searcher)
        {
            try
            {
                var user = userRep.Find(id);
                user.Flag = 1;  // 0:Enable, 1: Disable
                userRep.Update(user);
                userRep.SaveChanges();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
            }
            return RedirectToAction("Grid", new { pageIndex = pageIndex, searcher = searcher });
        }

        /// <summary>
        /// Edit user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="pageIndex">Page index.</param>
        /// <param name="searcher">Filter condtions.</param>
        /// <returns>User form.</returns>
        public ActionResult Edit(string id, int pageIndex, Searcher searcher)
        {
            TempData["pageIndex"] = pageIndex;
            TempData["searcher"] = searcher;
            //ViewBag.pageIndex = pageIndex;
            //ViewBag.searcher = searcher;
            return View(userRep.Find(id));
        }

        /// <summary>
        /// Edit user.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <param name="forms">Form collections about user item.</param>
        /// <returns>Edit result, if success then redirect to list, else show validation errors.</returns>
        [HttpPost]
        public ActionResult Edit(string id, FormCollection forms)
        {
            var model = userRep.Find(id);
            if (TryUpdateModel(model))
            {
                try
                {
                    userRep.SaveChanges();
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(ex.Message, ex);
                }
                return RedirectToAction("Index");
            }
            return View(model);
        }

        /// <summary>
        /// Reset user password.
        /// </summary>
        /// <param name="id">User id.</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Reset(string id)
        {
            var user = userRep.Find(id);
            user.Password = CM.GenDefaultPassword();
            try
            {
                userRep.Update(user);
                userRep.SaveChanges();
                return Json("重置成功", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message, ex);
                return Json("出错了", JsonRequestBehavior.AllowGet);
            }
        }


        [ActionName("Export")]
        [HttpPost]
        public JsonResult PreExport(Searcher searcher)
        {
            var pred = UserSpecification.Get_User_Pred(searcher);

            var list = userRep.GetList<User>().Where(m => m.RoleID == Constant.Agency);
            bool hasdata = list.Where(pred).Count() > 0;
            return Json(new { searcher = searcher.ToString(), hasdata = hasdata });
        }


        /// <summary>
        /// Export dismachine report.
        /// </summary>
        /// <param name="searcher">Filter conditions.</param>
        /// <returns>Excel file.</returns>
        public void Export(Searcher searcher)
        {
            var pred = UserSpecification.Get_User_Pred(searcher);
            var list = userRep.GetList<User>().Where(m => m.RoleID == Constant.Agency);

            var lst = list.Where(pred).OrderByDescending(d => d.CreateDate).ToList();

            string[] filters = new string[] {
                "UserName", "Name", "ContactName", "Tel", "Mobile", "Address", "QQ",
                "Email", "Remark"};

            var dt = lst.ToDataTable(filters);
            string[] columnname = new string[] { "用户名", "代理商名称", "联系人名称", "联系方式", "手机", "地址", "QQ", "邮箱", "备注"};

            ExcelHelper.ExportToExcel(null, "代理商报表", dt, columnname, filters, false);
        }
    }
}
